<template>
  <div class="app-page">  
    <Header></Header>
    <div class="designer">
      <Graphics></Graphics>
      <a-dropdown
        :trigger="['contextmenu']"
        @visibleChange="handleMenuVisibleChange"
      >
        <View />
        <template #overlay>
          <a-menu class="canvas-context-menu" @click="handleMenuClick">
            <template v-for="(vo, idx) in menuLists">
              <template v-if="vo.visible == true">
                <template v-if="vo.title == 'divider'">
                  <a-menu-divider :key="idx" />
                </template>
                <template v-else>
                  <a-menu-item
                    :disabled="vo.disabled"
                    :key="idx"
                    :data="vo.data"
                    :title="vo.title"
                  >
                    <span>{{ vo.title }}</span>
                    <span>{{ vo.keyCode }}</span>
                  </a-menu-item>
                </template>
              </template>
            </template>
          </a-menu>
        </template>
      </a-dropdown>
      <template v-if="activePen && multiPen">
        <Appearance ref="appearanceRef" />
      </template>
      <template v-else>
        <Props :data="propsData" />
      </template>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, nextTick } from 'vue';
  import { storeToRefs } from 'pinia';
  import { Pen } from '@meta2d/core';
  import { useCanvasStore } from '../store/canvas';
  import type { MenuProps } from "ant-design-vue";

  import Header from '../components/Header.vue';
  import Graphics from '../components/Graphics.vue';
  import View from '../components/View.vue';
  import Props from '../components/Props.vue';
  import Appearance from '../components/Appearance.vue';

  import { menus } from "@/utils/operationGroups.ts";
  import {LOCK_STATE_DATA as lockState, PEN_TYPE as PenType} from "@/utils/index";
  import { useSelection } from "@/services/selections";

  const { selections } = useSelection();
  
  let activePen = ref(false); // 选中的画笔状态
  let multiPen = ref(false); // 多个画笔状态
  let pens = ref([]); // 画笔数组

console.log('menus', menus)

  const canvasStore = useCanvasStore();
  const { meta2dDatas } = storeToRefs(canvasStore);
  let menuLists = ref(menus);
  let propsData = ref({});
  const appearanceRef = ref<InstanceType<typeof Appearance>>();


  let timer: any;
  function save() {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      const data: any = meta2d.data();
      meta2dDatas.value = data;
      propsData.value = data;
      // localStorage.setItem('meta2d', JSON.stringify(data));
      timer = undefined;
    }, 1000);
  }

  onMounted(() => {
    meta2d.on('scale', save);
    meta2d.on('add', save);
    meta2d.on('opened', save);
    meta2d.on('undo', save);
    meta2d.on('redo', save);
    meta2d.on('add', save);
    meta2d.on('delete', save);
    meta2d.on('rotatePens', save);
    meta2d.on('translatePens', save);

  // 记录是否有选中多个图元
  meta2d.on("active", (args: any) => {
    pens.value = args;
    console.log('args', args)
    if (args.length >= 1) {
      activePen.value = true;
    }
    if (args.length > 1) {
      multiPen.value = true;
      console.log('args1111111111', args, pens.value)
      nextTick(() => {
      //   proxy.$refs.appearance.init(pens.value);
      console.log('arg222222222222', args, pens.value)
        if(appearanceRef.value) {
          console.log('arg333333333333', args, pens.value)
          appearanceRef.value.init(pens.value);
        }
      });
    } else {
      multiPen.value = false;
    }
    if (args.length == 1) {
      let [pen] = args;
      if (pen["type"] !== undefined) {
        menuLists.value.map((_: any) => {
          switch (pen["type"]) {
            case 0:
              // 节点
              switch (_.data) {
                case "node":
                  {
                    _.visible = false;
                  }
                  break;
                case "line":
                case "penType":
                  {
                    _.visible = true;
                  }
                  break;
              }
              break;
            case 1:
              // 连线
              switch (_.data) {
                case "node":
                case "penType":
                  {
                    _.visible = true;
                  }
                  break;
                case "line":
                  {
                    _.visible = false;
                  }
                  break;
              }
              break;
          }
        });
      }
    }
  });
  // 清空高亮画笔
  meta2d.on("inactive", () => {
    activePen.value = false;
    multiPen.value = false;
    pens.value = [];
  });

  // GET_IMAGE_PATH("rotate", "rotate.cur").then((rotateCursor: string) => {
  //   meta2d.setOptions({
  //     rotateCursor,
  //   });
  // });
  });

/**
 * 处理鼠标右键菜单显示
 */
const handleMenuVisibleChange = (e: any) => {
  console.log('handleMenuVisibleChange', e)
  let { pen } = selections;
  console.log('pen', pen)
  console.log('pens', pens)
  if (e) {
    if (pen !== undefined) {
      menuLists.value.some((_: any) => {
        if (_.data == "delete") {
          _.disabled = false;
          _.visible = true;
        }
      });
      switch (pen.locked) {
        case 0:
          menuLists.value.some((_: any) => {
            if (_.data == "locked") {
              _.disabled = false;
            }
            if (_.data == "unlocked") {
              _.disabled = true;
              _.visible = false;
            }
          });
          break;
        case 2:
          menuLists.value.some((_: any) => {
            if (_.data == "locked") {
              _.disabled = true;
              _.visible = false;
            }
            if (_.data == "unlocked") {
              _.disabled = false;
              _.visible = true;
            }
          });
          break;
        default:
          menuLists.value.some((_: any) => {
            if (_.data == "locked") {
              _.disabled = false;
            }
            if (_.data == "unlocked") {
              _.disabled = true;
              _.visible = false;
            }
          });
          break;
      }
      if (pen["children"]) {
        if (pen.children.length !== 0) {
          menuLists.value.map((_: any) => {
            if (_.data == "locked") {
              _.disabled = false;
            }
            if (_.data == "uncombine") {
              _.visible = true;
            }
          });
        }
      }
    } else {
      if (pens.value.length !== 0) {
        menuLists.value.map((_: any) => {
          if (
            ["combine", "delete"].includes(_.data) &&
            activePen.value == true
          ) {
            _.visible = true;
            _.disabled = false;
          }
        });
      }
    }
  } else if (!e) {
    menuLists.value.map((_: any) => {
      switch (_.data) {
        case "combine":
        case "uncombine":
        case "node":
        case "line":
        case "penType":
          _.visible = false;
          break;
        case "delete":
          _.disabled = true;
          break;
      }
    });
  }
}

  /**
 * 右键菜单事件集合
 */
const handleMenuClick: MenuProps["onClick"] = (e: any) => {
  console.log('handleMenuClick', e)
  let { pen } = selections;
  let list = menuLists.value;
  if (pen || pens.value.length > 0) {
    console.log(e.item.data);
    switch (e.item.data) {
      // 置顶
      case "top":
        meta2d.top(pen as Pen);
        break;
      // 置顶
      case "bottom":
        meta2d.bottom(pen as Pen);
        break;
      // 上一图层
      case "up":
        meta2d.up(pen as Pen);
        break;
      // 下一图层
      case "down":
        meta2d.down(pen as Pen);
        break;
      // 组合为状态
      case "combine": {
        list.some((_: any) => {
          if (_.data == "combine") {
            _.visible = false;
          }
          if (_.data == "uncombine") {
            _.visible = true;
          }
        });
        if (e.item.title == "组合") {
          meta2d.combine(pens.value);
        } else {
          meta2d.combine(pens.value, 0);
        }
        break;
      }
      // 取消组合为状态
      case "uncombine": {
        list.some((_: any) => {
          if (_.data == "combine") {
            _.visible = true;
          }
          if (_.data == "uncombine") {
            _.visible = false;
          }
        });
        meta2d.uncombine(pen as Pen);
        break;
      }
      case "locked": {
        list.some((_: any) => {
          if (_.data == "locked") {
            _.visible = false;
          }
        });
        pens.value.map((_: any) => {
          meta2d.setValue(
            { id: _.id, locked: lockState.DisableMove },
            { render: false }
          );
        });
        break;
      }
      case "unlocked": {
        list.some((_: any) => {
          if (_.data == "locked") {
            _.visible = true;
          }
        });
        pens.value.map((_: any) => {
          meta2d.setValue(
            { id: _.id, locked: lockState.None },
            { render: false }
          );
        });
        break;
      }
      // 删除
      case "delete":
        if (pens.value.length !== 0) {
          meta2d.delete(pens.value);
        }
        break;
      // 剪切
      case "cut":
        if (pens.value.length !== 0) {
          meta2d.cut(pens.value);
        }
        break;
      // 复制
      case "copy":
        if (pens.value.length !== 0) {
          meta2d.copy(pens.value);
        }
        break;
      case "node":
        {
          meta2d.setValue({
            id: pen?.id,
            type: PenType.Node,
          });
        }
        break;
      case "line":
        {
          meta2d.setValue({
            id: pen?.id,
            type: PenType.Line,
          });
        }
        break;
      default:
        break;
    }
  }
  switch (e.item.data) {
    // 恢复
    case "redo":
      meta2d.redo();
      break;
    // 撤销
    case "undo":
      meta2d.undo();
      break;
    // 粘贴
    case "paste":
      meta2d.paste();
      break;
    default:
      break;
  }
  meta2d.inactive();
  meta2d.render();
  save();
};

</script>

<style lang="scss" scoped>
.app-page {
  height: 100vh;
  overflow: hidden;
  .designer {
    display: grid;
    height: calc(100vh - 40px);
    grid-template-columns: 200px 1fr 301px;
  }
}
</style>  